package com.wft.design.upms.controller;

import com.wft.design.common.security.annotation.PreAuthorize;
import com.wft.design.common.security.bean.AccessToken;
import com.wft.design.common.security.bean.Authentication;
import com.wft.design.common.security.bean.LoginParameter;
import com.wft.design.common.security.service.AccessTokenService;
import com.wft.design.common.security.service.AuthenticationManager;
import com.wft.design.upms.entity.SysUserInfo;
import com.wft.design.upms.mapper.SysUserRoleMapper;
import com.wft.design.upms.service.SysUserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author WFT
 * @date 2020/1/2
 * description: 认证控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/auth")
public class AuthenticationController {

    private final SysUserInfoService userInfoService;
    private final AccessTokenService accessTokenService;
    private final AuthenticationManager authenticationManager;
    private final SysUserRoleMapper userRoleMapper;

    /**
     * 系统账号登陆
     * @param parameter 请求参数
     * @return com.wft.design.common.security.bean.AccessToken
     */
    @PostMapping(value = "/login")
    public AccessToken login(@Validated @RequestBody LoginParameter parameter){
        //  获取账号信息
        SysUserInfo userInfo = this.userInfoService.selectByUsername(parameter.getUsername());
        Assert.notNull(userInfo,"用户名不存在");
        Assert.isTrue(userInfo.getLockFlag() == 0,"账号被锁定,请与管理员联系");
        //  校验密码
        String cipherText = this.userInfoService.encryption(userInfo.getPassword(),parameter.getSalt());
        Assert.isTrue(cipherText.equals(parameter.getPassword()),"用户名或密码错误");
        //  获取账号的权限列表
        List<String> list = this.userRoleMapper.selectAuthorities(userInfo.getId());
        return this.accessTokenService.generateAccessToken(new Authentication(userInfo.getId(),list),null);
    }

    /**
     * 退出登录
     * @param request 请求
     */
    @PreAuthorize
    @GetMapping(value = "/logout")
    public void logout(HttpServletRequest request){
        this.authenticationManager.removeAuthentication(request);
    }


}
